<template>
  <a-cascader
    v-model:value="nowValue"
    :options="options"
    :load-data="loadData"
    placeholder="请选择"
    @change="changeSelect"
    showCheckedStrategy="Cascader.SHOW_CHILD"
    change-on-select
  />
</template>
<script lang="ts">
import { defineComponent, ref, watch } from "vue";
import { defHttp } from "/@/utils/http/axios";
import type { CascaderProps } from "ant-design-vue";

export default defineComponent({
  props: {
    value: {
      type: String,
      default: "",
    },
  },
  emits: ["input"],
  setup(props, { emit }) {
    let nowValue = ref([]);
    watch(
      props,
      (n) => {
        nowValue.value = [n.value];
      },
      { deep: true }
    );
    nowValue.value = [props.value];
    const options = ref([]);

    async function getOptions() {
      let res = await defHttp.get({ url: "Organizations/Select" });
      console.log(res.data);
      options.value = res.data.map((item) => {
        return {
          label: item.name,
          value: item.id,
          isLeaf: false,
        };
      });
    }

    getOptions();

    const loadData: CascaderProps["loadData"] = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      defHttp
        .get({ url: `Wards/Select`, params: { organizationId: targetOption.value } })
        .then((res) => {
          targetOption.loading = false;
          targetOption.children = res.data.map((item) => {
            return {
              label: item.name,
              value: item.id,
            };
          });
          options.value = [...options.value];
        });
    };

    function changeSelect(e) {
      emit("input", Array.isArray(e) ? e[e.length - 1] : e);
    }
    console.log(nowValue, "nowValue");
    return {
      nowValue,
      options,
      loadData,
      changeSelect,
    };
  },
});
</script>
